import http = require('http');
import express = require('express');
import bodyParser = require('body-parser');
import session = require('express-session');

import Log from "../common/RunLog";

export default class WebServer{
    private expressApp : express.Express ;
    private label:string = "";
    public constructor(label:string, options?:Object){
        this.expressApp = express();
        this.label = label;
        this.init(options);
        this.initroute();
    }

    private init(options?:{[key:string]:any}):void{
        this.expressApp.use(bodyParser.json());
        this.expressApp.use(bodyParser.urlencoded({ extended: true }));
        if(options!=undefined && options["sessionChecker"]){
            this.expressApp.use(session({
                secret: '1234567890QWERTY',
                resave: true,
                saveUninitialized: true
            }));
        }
        if(options!=undefined && typeof options["viewengine"] == "string"){
            this.expressApp.set('view engine', options["viewengine"]);
            this.expressApp.use('/static', express.static(__dirname + '/../../static'));
            this.expressApp.use('/public/uploads', express.static(__dirname + '/../../public/uploads'));
        }
        
    }

    protected initroute(){

    }
    protected start(port:number, myaddress:string = "0.0.0.0", onStart?:()=>void){
        let _this = this;
        http.createServer(this.expressApp).listen(port, myaddress, function () {
            Log.output('('+_this.label+') listening on port '+port+'!');
            if(onStart != undefined){
                onStart();
            }
            
        });
    }

    public stop(){
        Log.output('('+this.label+') stop running.');
    }

    //mehtod = "get" | "post" | "all"
    public addRoutePath(path:string, method:string, handler:(req: express.Request,res: express.Response)=>void){
        let route:any = this.expressApp.route(path);
        if(method == "all"){
            route.all(handler);
        }
        else if(method == "get"){
            route.get(handler);
        }
        else if(method == "post"){
            route.post(handler);
        }
    }

    /**
     * 
     */
    public addErrorHandler() {
        this.expressApp.use(function(err:any, req: express.Request,res: express.Response, next:express.NextFunction) {
            console.error(err.stack);
            res.status(500).send('Something broke!');
          });        
    }
}